package com.hzw.saas.common.config.configuration;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.JSR310DateTimeDeserializerBase;
import cn.hutool.core.date.LocalDateTimeUtil;

/**
 * LocalDateTime解析器
 * 主要用于处理 "yyyy-MM-dd" 日期类pattern到LocalDateTime
 *
 * @author zzl
 * @since 07/15/2021
 */
public class MyDateTimeDeserializer extends JSR310DateTimeDeserializerBase<LocalDateTime> {

    private static final long serialVersionUID = 1L;

    private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

    public static final MyDateTimeDeserializer INSTANCE = new MyDateTimeDeserializer();

    private MyDateTimeDeserializer() {
        this(DEFAULT_FORMATTER);
    }

    public MyDateTimeDeserializer(DateTimeFormatter formatter) {
        super(LocalDateTime.class, formatter);
    }

    /**
     * Since 2.10
     */
    protected MyDateTimeDeserializer(MyDateTimeDeserializer base, Boolean leniency) {
        super(base, leniency);
    }

    @Override
    protected MyDateTimeDeserializer withDateFormat(DateTimeFormatter formatter) {
        return new MyDateTimeDeserializer(formatter);
    }

    @Override
    protected MyDateTimeDeserializer withLeniency(Boolean leniency) {
        return new MyDateTimeDeserializer(this, leniency);
    }

    @Override
    protected MyDateTimeDeserializer withShape(JsonFormat.Shape shape) { return this; }

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        return LocalDateTimeUtil.parse(parser.getText().trim(), super._formatter);
    }
}
